package main

import (
	
	// "mylib/hupu"
	"mylib/win007"
	"time"
	"strings"
	"strconv"
	"log"
	"net/smtp"
	"encoding/xml"
	"fmt"
	"net/http"
	"io/ioutil"
	"code.google.com/p/mahonia"
)

//临时测试，成功后规到编译里

type C struct {
	S    string    `xml:"s"`
	M    M  `xml:"m"`
}

type M struct{
	H []string `xml:"h"`
}

func Bar(){
	
	//加了二天
	_day := time.Now().Add( 1 * 24 * time.Hour).Format("2006-01-02")
	_time := strconv.FormatInt(time.Now().Unix(),10)
	_xmlurl := "http://bf.win007.com/nba_date.aspx?date="+ _day +"&h=0&m=0&t=" + _time
	resp,err := http.Get(_xmlurl)
	if err != nil{
		panic(err)
	}
	defer resp.Body.Close()

	var c C

	body,err := ioutil.ReadAll(resp.Body)


	var dec mahonia.Decoder
 

    dec = mahonia.NewDecoder("gb2312")
    if ret, ok := dec.ConvertStringOK(string(body)); ok {
    	ret = strings.Replace(ret, "<?xml  version=\"1.0\" encoding=\"gb2312\"?>", "",-1)
    	err = xml.Unmarshal([]byte(ret), &c)
	    if err != nil {
	        log.Fatal(err)
	    }

	    _s := strings.Split(c.S, ",")
     

        for i := range _s {
        	if _s[i] != "" {
        		_ss := strings.Split(_s[i],"^")
        		win007.CreateLeague(_ss[0],_ss[1])
        	}
        }
        //fmt.Println(c.M.H[0])
        //fmt.Println(len(c.M.H))
    }

	
}

func SendMail(user, password, host, to, subject, body, mailtype string) error{
    hp := strings.Split(host, ":")
    auth := smtp.PlainAuth("", user, password, hp[0])
    var content_type string
    if mailtype == "html" {
        content_type = "Content-Type: text/"+ mailtype + "; charset=UTF-8"
    }else{
        content_type = "Content-Type: text/plain" + "; charset=UTF-8"
    }
 
    msg := []byte("To: " + to + "\r\nFrom: " + user + "<"+ user +">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
    send_to := strings.Split(to, ";")
    err := smtp.SendMail(host, auth, user, send_to, msg)
    return err
}

func Foo(){

	 user := "tmd_sb@163.com"
    password := "273511"
    host := "smtp.163.com:25"
    to := "tmd_sb@163.com"
 
    subject := "Test send email by golang"
 
    body := `
    <html>
    <body>
    <h3>
    "Test send email by golang"
    </h3>
    </body>
    </html>
    `
    fmt.Println("send email")
    err := SendMail(user, password, host, to, subject, body, "html")
    if err != nil {
        fmt.Println("send mail error!")
        fmt.Println(err)
    }else{
        fmt.Println("send mail success!")
    }
}




func main(){
	
	// win007.Foo()
	// win007.InitDb()

	// win007.CreateLeague("a","b")
	Foo()
	// Bar()


	// hupu.Foo()
	// hupu.InitDb()		//测试生成表
	// hupu.InitTeam()		//测试抓取球队数据

}